<?php

namespace Modules\Auth\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller as BaseController;
use Modules\Auth\Models\User;
use Illuminate\Support\Facades\Hash;

class LoginController extends BaseController
{
    // 登录
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);
        $user = User::where('email', $credentials['email'])->first();
        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message'=>'登录失败：邮箱或密码错误','status'=>401],401);
        }
        $token = $user->createToken('auth_token')->plainTextToken;
        return $this->respondWithToken($token, $user);
    }

    // 登出（删除当前 token）
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message'=>'已登出']);
    }

    // 获取当前登录用户
    public function me(Request $request)
    {
        return response()->json($request->user());
    }

    // 刷新 token（本质是重新发一个）
    public function refresh(Request $request)
    {
        $user = $request->user();
        $request->user()->currentAccessToken()->delete();
        $token = $user->createToken('auth_token')->plainTextToken;
        return $this->respondWithToken($token, $user);
    }

    // 统一返回格式
    protected function respondWithToken($token, $user)
    {
        return response()->json([
            'access_token'=>$token,
            'token_type'=>'Bearer',
            'user'=>$user
        ]);
    }
}
